<template>
  <header id="boxFixed" :class="state.headerFixed? 'isFixed' : ''">
    <a class="logo" href="/">进击的Kevin</a>
    <ul class="menu-list">
      <li class="menu-item" v-for="(item, index) in menuList" :key="index">
        <router-link :to="item.link">{{ item.name }}</router-link>
      </li>
    </ul>
  </header>
</template>

<script lang="ts" setup>
import { reactive, onMounted, nextTick, onUnmounted } from "vue";

interface MenuOptions {
  name: string;
  link: string;
  show?: boolean;
}

// state
const menuList: MenuOptions[] = reactive([
  {
    name: "首页",
    link: "/",
  },
  {
    name: "归档",
    link: "/archive",
  },
  {
    name: "留言",
    link: "/archive",
  },
  {
    name: "关于",
    link: "/about",
  },
]);

const state = reactive({
  offsetTop: 0,
  offSetHeight: 0,
  headerFixed: false
});

/**
 * @Note Header吸顶效果
 *  1. 监听页面滚动状态
 *  2. 计算元素吸顶到页面顶部的距离，确定吸顶时机（元素高度固定时，可以直接写死，省略这一步）
 *  3. 判断页面滚动距离
 */

// 监听dom渲染完成
const initHeight = () => {
  nextTick(() => {
    const header = document.querySelector("#boxFixed") as HTMLElement;
    // 得到top的距离
    state.offsetTop = header.offsetTop;
  });
};

// 滚动的监听回调
const handleScroll = () => {
  // 得到页面滚动的距离
  const scrollTop =  window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  // 判断页面滚动的距离是否大于吸顶元素的位置
  state.headerFixed = scrollTop > state.offsetTop;
};

// lifecycle
onMounted(() => {
  document.addEventListener("scroll", handleScroll);
  initHeight();
});

onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
});
</script>

<style lang="scss" scoped>
header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 60px;
  padding: 0 390px;
  background: #000;
  .menu-list {
    display: flex;
    .menu-item {
      margin-left: 60px;
      color: #fff;
    }
  }
}

.isFixed {
  position: fixed;
  top: 0;
  z-index: 999;
}
</style>